package com.white.hot.controller.wx;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.white.hot.constant.ConstantInfo;
import com.white.hot.controller.BaseController;
import com.white.hot.dto.resp.BaseResp;
import com.white.hot.dto.resp.MapInfo;
import com.white.hot.dto.resp.WXPayResp;
import com.white.hot.utils.TextUtils;
import com.white.hot.utils.XMLUtil;


@Controller
@RequestMapping("/wxpay")
public class WXPayController extends BaseController
{
	//获取预支付订单号的链接
	public static final String UNIFIED_ORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
	//微信开发平台应用id
//	public static final String APPID = "wxd8b01e744158047f";
	public static final String APPID = "wx0fa3e6f18744566e";
	//应用对应的凭证
//	public static final String APP_SECRET = "0a54e74d7358f3d49016a255e176ed0d";
	public static final String APP_SECRET = "16b9fabcc5ffccb54adeda8e53822933";
	//微信支付分配的商户号
//	public static final String MCH_ID = "1430280902";
	public static final String MCH_ID = "1382226802";
	//API密钥，在商户平台设置
//	public static final String API_KEY="201702161038zKingSoftLiHaiJing02";
	public static final String API_KEY="3030bb26a8ecd492c4604a8b6250167A";
	//验证ip合法性的正则
	public String ipRegax = "^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])"
			+ "\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)"
			+ "\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)"
			+ "\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$";
	
	@RequestMapping("/getPrepayId")
	@ResponseBody
	private Object getPrepayId(
			@RequestParam(value="body") String commodity, 
			@RequestParam(value="total_fee") String price,
			@RequestParam(value="spbill_create_ip") String clientIp)
	{
		BaseResp br = new BaseResp();
		if(TextUtils.isEmpty(commodity) || TextUtils.isEmpty(price) || TextUtils.isEmpty(clientIp))
		{
			br.setStatus(ConstantInfo.RSC_PARAM_INCOMPLETE);
			br.setInfo(ConstantInfo.RSS_PARAM_INCOMPLETE);
			return br;
		}else
		{
			int fee;
			try
			{
				fee = Integer.parseInt(price);
				String orderId = "no orderid generated";
				if(fee < 1)
				{
					return buildParamIllegalResp(br);
				}else
				{
					if(!clientIp.matches(ipRegax))
					{
						return buildParamIllegalResp(br);
					}else
					{
						SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();						
						parameters.put("appid", APPID);
						parameters.put("mch_id", MCH_ID);
						parameters.put("nonce_str", getOutTradeNo20());  //随机字符串，不长于32位。推荐随机数生成算法
						parameters.put("body", commodity);  			//商品描述
						orderId = getOutTradeNo20();
						parameters.put("out_trade_no", orderId);  		//商户系统内部的订单号,32个字符内、可包含字母(自定义，唯一)
						parameters.put("total_fee", price);  			//订单总金额，单位为分
						parameters.put("spbill_create_ip", clientIp);   //用户端实际ip
						parameters.put("notify_url", "http://"+ "" +":8080/MavenDemo/pay/alipay_notify");
						parameters.put("trade_type", "APP");  			//支付类型(JSAPI、 NATIVE、 APP)
						//用户在商户 appid 下的唯一标识， trade_type 为 JSAPI时，此参数必传，获取方式见表头说明
						//parameters.put("openid", "o7W6yt9DUOBpjEYogs4by1hD_OQE"); 
						parameters.put("attach","userId"); 				//附加数据，会在支付回调方法中原样返回
						String sign = WXPayUtils.createSign("UTF-8", parameters, API_KEY);
						parameters.put("sign", sign);
						String resStr = WXPayUtils.httpsRequest(UNIFIED_ORDER_URL, "POST", WXPayUtils.getRequestXml(parameters));
						if(TextUtils.isEmpty(resStr))
						{
							return buildInnerErrorResp(br);
						}else
						{
							WXPayResp wr = WXPayUtils.decodeXml(resStr);
							wr.api_safe_key = API_KEY;
							wr.order_id = orderId;
							MapInfo mi = new MapInfo();
							mi.setWxpayResp(wr);
							br.setMapInfo(mi);
							return buildSuccessResp(br);
						}
					}
				}
			} catch (NumberFormatException  e)
			{				
				return buildParamIllegalResp(br);
			}
		}
	}

	@RequestMapping("/wxpay_notify")
	public void alipayNotify(HttpServletResponse response,HttpServletRequest request)
	{
		ServletOutputStream out;
		try
		{
			out = response.getOutputStream();
			String inputLine;
			StringBuilder notityXml = new StringBuilder();
			String resXml = "";
			while ((inputLine = request.getReader().readLine()) != null)
			{
				notityXml.append(inputLine);
			}
			request.getReader().close();
			Map<Object, Object> map = XMLUtil.parseXmlToList(notityXml.toString());
			String return_code = map.get("return_code").toString(); // 返回状态码:SUCCESS/FAIL
			 String return_msg = map.get("return_msg").toString();
			// //返回信息，如非空，为错误原因

			if ("SUCCESS".equals(return_code))
			{
				// 确认支付支付成功
				resXml = "<xml>"
						+ "<return_code><![CDATA[SUCCESS]]></return_code>"
						+ "<return_msg><![CDATA[OK]]></return_msg>"
						+ "</xml> ";
			} else
			{
				// 确认支付支付失败
				resXml = "<xml>"
						+ "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[报文为空]]></return_msg>"
						+ "</xml> ";
			}

			out.write(resXml.getBytes());
			out.flush();
			out.close();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	
	}

}
